#include "stm32f10x.h"                  // Device header
#include "Menu_table.h"
#include "OLED.h"
#include "Timer.h"
#include "Key.h"

void Key_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;					//定义GPIO结构体
	EXTI_InitTypeDef EXTI_InitStructure;					//定义EXTI(外部中断)结构体
	NVIC_InitTypeDef NVIC_InitStructure;					//定义NVIC(嵌套向量中断)结构体
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE); //开启时钟
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;							//上拉输入
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;	
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;						//输出频率
	GPIO_Init(GPIOA, &GPIO_InitStructure);									//结构体配置完成初始化
	
	/*AFIO选择中断引脚*/
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource0);				//将外部中断的0号线映射到GPIOA，即选择PA0为外部中断引脚
	
    EXTI_InitStructure.EXTI_Line = EXTI_Line0;								//选择EXIT事件线
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;						//EXTI为中断模式
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;			//双边沿中断
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;								//使能中断
    EXTI_Init(&EXTI_InitStructure);
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);							//配置优先级分组：抢占优先级和子优先级
	
	NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn ;						//中断源
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;							//使能中断通道
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;				//抢占优先级
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;						//子优先级
	NVIC_Init(&NVIC_InitStructure);
	
}

uint8_t APPTOIN_MUTEX = 1;//程序互斥锁
void EXTI0_IRQHandler(void)
{
	static uint8_t Keystate = 0;	//静态按键状态 0 -- 松开  1 -- 按下
	
	if(EXTI_GetITStatus(EXTI_Line0) != RESET) 
	{
		if(KEY_STATA0 && Keystate) 
		{
			Keystate = 0;			//松开按键
			TIM_Cmd(TIM2, DISABLE);	//关闭定时器
			if((Time_Count > 3) && (Time_Count < 200)) 
			{
				if(++Keyval_Count >= 2) 
				{//双击
					taskIndex = TaskTable[taskIndex].Enter;//双击表示确认键
					OLED_Clear();
				};
			}
			if((Keyval_Count >= 2) || (Keyval_Count == 0)) 
			{
				Keyval_Count = 0;
				APPTOIN_MUTEX = 1;//关闭互斥
			}
			else 
			{ 
				Time_Count = 0;		//清空定时器溢出次数
				TIM_Cmd(TIM2, ENABLE);	//启动定时器
			}
		}
		else if(!KEY_STATA0 && !Keystate)
		{
			
			Keystate = 1;			//按下按键
			Time_Count = 0;		//清空定时器溢出次数
			TIM_Cmd(TIM2, ENABLE);	//启动定时器
			APPTOIN_MUTEX = 0;	//开启互斥
		}
		EXTI_ClearITPendingBit(EXTI_Line0);	//清除中断标志
	}
}


